<template>
    <div class="live-form">
        <h3 style="padding: 3px;">编辑</h3>
        <Row>
            <Col span="14">
            <Form class="form-input" ref="eventForm" :model="eventForm" label-position="top" :rules="liveInfoRules">
                <FormItem label="直播标题" style="font-size: 14px;" prop="eventTitle">
                    <Input v-model="eventForm.eventTitle"></Input>
                </FormItem>
                <FormItem label="直播时间" prop="eventStartTime">
                    <DatePicker  v-model="eventForm.eventStartTime"
                                 type="datetime"
                                 format="yyyy-MM-dd HH:mm"
                                 placeholder="选择日期"
                                 :options="dateOptions"></DatePicker>
                </FormItem>
                <FormItem label="活动类别" prop="eventTypeId">
                    <Select v-model="eventForm.eventTypeId" placeholder="请选择活动类别" style="width:200px">
                        <Option v-for="item in eventTypes"  :value="item.liveTypeId" :key="item.liveTypeId">
                            {{ item.typeName }}
                        </Option>
                    </Select>
                    <Button type="ghost" icon="ios-plus-empty" @click="addType" ></Button>
                </FormItem>
                <FormItem label="是否录制">
                    <Switch v-model="eventForm.enableRecord">
                        <span slot="open">开</span>
                        <span slot="close">关</span>
                    </Switch>
                    <span style="margin-left: 10px">启动录制后即可回看</span>
                </FormItem>
                <FormItem label="直播描述" prop="eventDesc">
                    <div id="editorElem" style="text-align:left;height:200px;">
                        <!--{{eventForm.eventDesc}}-->
                    </div>
                    <div class="limit">
                        当前已输入 <span>{{nowLength}}</span> 个字符，您还可以输入 <span>{{SurplusLength}}</span> 个字符。
                    </div>
                </FormItem>
            </Form>
            </Col>
            <Col span="10" class="form-input img-select">
            <Form class="" label-position="top">

                <FormItem  label="视频封面">
                    <Card style="text-align:center; width: 100%; height: auto">
                        <div style="">
                            <img v-if="eventForm.livePoster" v-model="eventForm.livePoster"  style="height: auto;width:100%" :src="eventForm.livePoster">
                            <h4 v-if="!eventForm.livePoster" style="text-align: center">请上传尺寸为1280*720px的图片,后缀名为png,gif,jpeg,jpg</h4>
                        </div>
                    </Card>
                </FormItem>
                <FormItem style="float: right">
                    <Upload action="//upload-z2.qiniu.com" :show-upload-list="false"
                            :format="['jpg','jpeg','png']"
                            :max-size="10000"
                            :on-format-error="handleFormatError"
                            :on-exceeded-size="handleMaxSize"
                            :on-progress="onProgress"
                            :data="uploadToken" :on-success="uploadPosterSuccess">
                        <Button type="ghost" :loading="loading" @click="getUploadToken">点击上传封面图片</Button>
                    </Upload>
                </FormItem>
            </Form>
            </Col>


        </Row>
        <Row class="submit-form">
            <!-- <Form class="" label-position="top" :rules="liveInfoRules">-->
            <Col span="24" style="text-align: center">
            <!-- <FormItem>-->
            <Button type="error" style="width: 120px" @click="submitForm('eventForm','eventFormPoster')" :loading="createLoading">更新</Button>
            <!-- </FormItem>-->
            <!--<FormItem>-->
            <Button style="margin-left: 20px;width: 120px">取消</Button>
            <!-- </FormItem>-->
            </Col>
            <!--</Form>-->
        </Row>
        <!--增加直播类别对话框-->
        <Modal
                v-model="addTypeModel"
                title="增加直播类别"
                :loading="addTypeLoading"
                @on-ok="submitType">
            <Input v-model="liveType" placeholder="请输入直播类别"></Input>
        </Modal>
    </div>
</template>

<script>
    import $ from 'jquery'
    import {getLiveTypes, getQiNiuToken , createLiveRoom, addLiveType, getOneLiveInfoById, updateLiveRoom} from '../../api/api'
    import {Message} from 'element-ui';
    import {VueEditor} from 'vue2-editor'
    import axios from 'axios'
    import {formatDate} from '../../utils/dateUtil'
    import E from 'wangeditor'
    export default {
        components: {
            VueEditor
        },
        computed: {
            nowLength: function () {
                return this.eventForm.eventDesc.length
            },
            SurplusLength: function () {   // 计算属性 获得当前输入字符长度
                let num = 1000 - Number(this.eventForm.eventDesc.length)
                if (num > 0) {
                    return num
                } else {
                    return 0
                }
            }
        },
        data(){
            return {
                addTypeModel:false,
                liveType:'',
                addTypeLoading:true,
                orgId:this.$store.state.orgId,
                dateOptions:{
                    disabledDate (date) {
                        return date && date.valueOf() < Date.now() - 86400000;
                    }
                },
                loading: false,
                createLoading:false,
                uploadToken: {
                    token: ''
                },
                poster: '',
                eventTypes: [],
                eventForm: {
                    liveRoomId:null,
                    eventTitle: null,
                    eventStartTime: null,
                    eventTypeId: null,
                    eventDesc:'',
                    livePoster:null,
                    enableRecord:false
                },
                liveInfoRules: {
                    eventTitle:{ required: true, message: '请填写直播间标题', trigger: 'blur' },
                    eventStartTime:{required: true, message: '请选择时间', trigger: 'change'},
                    eventTypeId:{required: true, type:'number', message: '请选择类别', trigger: 'change'},
                    eventDesc:{required: true, message: '请填写直播间描述信息', trigger: 'change'},
                },

            }
        },
        methods: {
            addType(){
                this.addTypeModel = true
            },
            submitType(){
                if (this.liveType){
                    let params = {
                        typeName: this.liveType,
                        orgId: this.orgId
                    }
                    addLiveType(params).then(res =>{
                        if (res.code == 0){
                            this.addTypeModel = false
                            this.setLiveTypes()
                        }
                    })
                }
            },

            uploadPosterSuccess(reponse, file){
                this.loading = false
                this.eventForm.livePoster = "http://owggex94j.bkt.clouddn.com/" + reponse.key
            },

            onProgress(){
                this.loading = true
            },
            handleFormatError (file) {
                this.$Notice.warning({
                    title: '文件格式不正确',
                    desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
                });
            },
            handleMaxSize (file) {
                this.$Notice.warning({
                    title: '超出文件大小限制',
                    desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
                });
            },
            submitForm(names){
                this.$refs['eventForm'].validate((valid) => {

                    if (valid) {
                        let date = new Date(this.eventForm.eventStartTime);
                        this.eventForm.eventStartTime = formatDate(date,"yyyy-MM-dd hh:mm:ss")
                        this.createLoading = true
                        updateLiveRoom(this.eventForm).then(response =>{
                            this.createLoading = false
                            this.$Message.success('更新成功！');
                        })
                    }
                })
            },
            getUploadToken(){
                getQiNiuToken().then(response => {
                    this.uploadToken.token = response.token
                })
            },
            setLiveTypes(){
                getLiveTypes(this.orgId).then(response => {
                    this.eventTypes = response.types
                })
            }

        },
        mounted: function () {
            //获取直播类别
            this.setLiveTypes()
            //初始化富文本编辑器
            var editor = new E('#editorElem')

            //配置菜单
            editor.customConfig.menus = [
                'head',  // 标题
                'bold',  // 粗体
                'italic',  // 斜体
                'underline',  // 下划线
                'foreColor',  // 文字颜色
                'backColor',  // 背景颜色
                'link',  // 插入链接
                'list',  // 列表
                'justify',  // 对齐方式
                'quote',  // 引用
                'emoticon',  // 表情
                'image',  // 插入图片
                'table',  // 表格
                'undo',  // 撤销
                'redo'  // 重复
            ]
            editor.customConfig.onchange = (html) => {
                this.eventForm.eventDesc = html
            }
            editor.customConfig.uploadImgServer = '//upload-z2.qiniu.com'
            editor.customConfig.uploadImgParams = {
                token: ''   // 属性值会自动进行 encode ，此处无需 encode
            }
            editor.customConfig.uploadFileName = 'file'
            editor.customConfig.uploadImgHooks = {
                success: function (xhr, editor, result) {

                },
                fail: function (xhr, editor, result) {
                    this.$Message.error('上传图片失败');
                },
                error: function (xhr, editor) {
                    this.$Message.error('上传图片出错');
                },
                timeout: function (xhr, editor) {
                    this.$Message.error('上传图片超时');
                },
                customInsert: function (insertImg, result, editor) {
                    var url = "http://owggex94j.bkt.clouddn.com/"+result.key
                    insertImg(url)
                }
            }
            editor.customConfig.customAlert = function (info) {
                this.$Message.error(info);
            }
            editor.customConfig.zIndex = 100
            editor.create()
            //获取直播间信息，更新
            getOneLiveInfoById(this.$store.state.operatedLiveRoomId).then(response =>{
                this.eventForm = response.liveRoom
                editor.txt.html(this.eventForm.eventDesc)
            })
            //editor.txt.html(this.eventForm.eventDesc)
            $('#editorElem').attr('style','height:auto;');
            //监听点击上传图片事件，随后获取token
            document.getElementById(editor.imgMenuId).addEventListener('click',function (event) {
                //上传前获取七牛上传凭证
                getQiNiuToken().then(res =>{
                    if (res.code == 0){
                        editor.uploadImg.editor.customConfig.uploadImgParams.token= res.token
                    }
                })
            },false)
        }

    }
</script>
<style scoped lang="less">
    /* table 样式 */
    table {
        border-top: 1px solid #ccc;
        border-left: 1px solid #ccc;
    }
    table td,
    table th {
        border-bottom: 1px solid #ccc;
        border-right: 1px solid #ccc;
        padding: 3px 5px;
    }
    table th {
        border-bottom: 2px solid #ccc;
        text-align: center;
    }

    /* blockquote 样式 */
    blockquote {
        display: block;
        border-left: 8px solid #d0e5f2;
        padding: 5px 10px;
        margin: 10px 0;
        line-height: 1.4;
        font-size: 100%;
        background-color: #f1f1f1;
    }

    /* code 样式 */
    code {
        display: inline-block;
        *display: inline;
        *zoom: 1;
        background-color: #f1f1f1;
        border-radius: 3px;
        padding: 3px 5px;
        margin: 0 3px;
    }
    pre code {
        display: block;
    }

    /* ul ol 样式 */
    ul, ol {
        margin: 10px 0 10px 20px;
    }
    .limit {
        margin-top:5px;
        float: right;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #20a0ff;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .submit-form {
        //margin-top: 20px;
    }

    .image-upload {
        width: 100%;
        height: 280px;
        //background-color: #18b566;
        text-align: center;
        border: 1px solid #bbbec4;
        line-height: 280px;
    }

    .ql-container {
        min-height: 20em;
        padding-bottom: 1em;
        max-height: 25em;
    }

    .img-select {
        padding: 25px 20px 10px;
    }

    .live-form {
        //padding: 20px;
    }

    .form-input {
        padding: 20px;
    }

    .timeSelect {
        margin-right: 20px;
    }

</style>
<style>
    .w-e-menu {
        /*z-index: 1 !important;*/
    }

    .ivu-form {

    .ivu-form-item-label {
        font-size: 14px !important;
    }

    }
</style>